package com.kkwrite.regimen.provider.service.item;

import com.kkwrite.regimen.common.constant.SortTypeEnum;
import com.kkwrite.regimen.common.entity.dto.item.ItemDetailDTO;
import com.kkwrite.regimen.common.entity.dto.order.OrderReviewQueryOutDTO;
import com.kkwrite.regimen.common.entity.dto.picture.PictureDTO;
import com.kkwrite.regimen.common.entity.dto.shop.PageableItemDTO;
import com.kkwrite.regimen.common.entity.dto.shopItem.ShopItemDTO;
import com.kkwrite.regimen.provider.domain.RegItemDO;
import com.kkwrite.regimen.provider.domain.RegOrderDO;
import com.kkwrite.regimen.provider.exception.ServiceException;
import com.kkwrite.regimen.provider.repository.RegItemRepository;
import com.kkwrite.regimen.provider.repository.RegShopItemRepository;
import com.kkwrite.regimen.provider.service.order.OrderService;
import com.kkwrite.regimen.provider.service.picture.PictureService;
import com.kkwrite.regimen.provider.service.review.ReviewService;
import com.kkwrite.regimen.provider.service.shop.ShopItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/** 
 * 类说明 
 *
 * @author Soosky Wang
 * @date 2018年7月20日 下午5:33:49 
 * @version 1.0.0
 */
@Service("itemService")
public class ItemServiceImpl implements ItemService {

	private static final Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

	@Resource(name = "regItemRepository")
	private RegItemRepository regItemRepository;
	
	@Resource(name = "regShopItemRepository")
	private RegShopItemRepository regShopItemRepository;
	
	@Resource(name = "pictureService")
	private PictureService pictureService;

	@Resource(name = "orderService")
	private OrderService orderService;
	
	@Resource(name = "reviewService")
	private ReviewService reviewService;
	
	@Resource(name = "shopItemService")
	private ShopItemService shopItemService;
	
	@Resource(name = "itemService")
	private ItemService itemService;
	
	@Override
	public ItemDetailDTO getItemDetail(Long itemId) throws ServiceException {
		if (logger.isDebugEnabled()) {
			logger.debug("ItemServiceImpl.getItemDetail(), itemId = " + itemId);
		}
		ItemDetailDTO itemDetailDTO = new ItemDetailDTO();

		// 查询项目
		RegItemDO regItemDO;
		try {
			regItemDO = regItemRepository.findById(itemId).orElse(null);
			if (regItemDO == null) {
				return null;
			}
			BeanUtils.copyProperties(regItemDO, itemDetailDTO);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("查询项目信息出错！ItemServiceImpl.getItemDetail(), itemId = " + itemId);
		}
		
		// 查询项目配图
		try {
			//TODO ownerType 写死了
			List<PictureDTO> pictureDTOs = pictureService.getOwerPictures(regItemDO.getItemId(), (short) 2);
			if (pictureDTOs != null && pictureDTOs.size() > 0) {
				itemDetailDTO.setPictures(pictureDTOs);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("查询项目配图出错！ItemServiceImpl.getItemDetail(), regItemDO = " + regItemDO);
		}
		
		return itemDetailDTO;
	}

    @Override
    public List<List<OrderReviewQueryOutDTO>> queryReview(Integer itemId) throws ServiceException {
        // 查询所有订单编号
		List<RegOrderDO> orderList = orderService.findByItemId(itemId);
		if (orderList == null || orderList.isEmpty()) {
			throw new ServiceException("订单不存在");
		}
		// 查询所有订单评价
		final List<List<OrderReviewQueryOutDTO>> reviewList = new ArrayList<>();
		orderList.forEach((order) -> {
			try {
				reviewList.add(reviewService.findByOrderCode(order.getOrderCode()));
			} catch (ServiceException e) {
				logger.error(e.getMessage(), e);
			}
		});
		return reviewList;
    }

    @Override
    public List<ItemDetailDTO> getIndexItemPageable(String city, Integer itemType,Integer sort, Integer sortType, Integer page, Integer pageSize) {
        String sortProperty = "discountPrice";
		// sort 排序方式 （1价格2人气3评价）
		if (sort == 2) {
			sortProperty = "2";
		} else if (sort == 3) {
			sortProperty = "3";
		}
		Sort.Direction direction = Sort.Direction.ASC;
		if (sortType.equals(SortTypeEnum.REVERSE_SEQUENCE.getValue())) {
			direction = Sort.Direction.DESC;
		}
		RegItemDO regItemDO = new RegItemDO();
		if (itemType != 3) {// 若前台没有传值，则置空
			
			regItemDO.setItemType(itemType);
		}
		Page<RegItemDO> pageData = regItemRepository.findAll(Example.of(regItemDO),new PageRequest(page, pageSize, new Sort(direction, sortProperty)));
		if (pageData.getTotalElements() <= 0) {
			return new ArrayList<>();
		}
		List<ItemDetailDTO> out = new ArrayList<>();
		List<RegItemDO> items = pageData.getContent();
		items.forEach((item) -> {
			ItemDetailDTO dto = new ItemDetailDTO();
			BeanUtils.copyProperties(item, dto);
			try {
				List<PictureDTO> pictureDTOs = pictureService.getOwerPictures(item.getItemId(), (short) 2);
				dto.setPictures(pictureDTOs);
				dto.setTotalPages(pageData.getTotalPages());
				dto.setTotalElements(pageData.getTotalElements());
				out.add(dto);
			} catch (ServiceException e) {
				logger.error(e.getMessage(), e);
			}
		});
		return out;
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer countShopNumByItemId(Long itemId,String city) throws ServiceException {
		try {
			return regShopItemRepository.countShopByItemId(itemId,city);
		} catch (Exception e) {
			logger.error("ItemServiceImpl.countShopByItemId(), itemId = {}", itemId);
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public void reviewCountPlus(int itemId, int reviewCount) {
		Assert.isTrue(reviewCount > 0, "reviewCount 不能小于等于0");
		Assert.isTrue(itemId > 0, "itemId 不能小于等于0");
		regItemRepository.findById((long) itemId).ifPresent((item) -> {
			item.setReviewCount(item.getReviewCount() + reviewCount);
			regItemRepository.save(item);
		});
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
    public void saleCountPlus(int itemId, int count) {
		regItemRepository.findById((long) itemId).ifPresent((item) -> {
			item.setSaleAmount(item.getSaleAmount() + count);
			regItemRepository.save(item);
		});
    }

	@Override
	public ItemDetailDTO getItemDetail(Long itemId, String city)
			throws ServiceException {
		if (logger.isDebugEnabled()) {
			logger.debug("ItemServiceImpl.getItemDetail(), itemId = " + itemId);
		}
		ItemDetailDTO itemDetailDTO = new ItemDetailDTO();

		// 查询项目
		RegItemDO regItemDO;
		try {
			regItemDO = regItemRepository.findById(itemId).orElse(null);
			if (regItemDO == null) {
				return null;
			}
			BeanUtils.copyProperties(regItemDO, itemDetailDTO);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("查询项目信息出错！ItemServiceImpl.getItemDetail(), itemId = " + itemId);
		}
		
		// 查询项目配图
		try {
			//TODO ownerType 写死了
			List<PictureDTO> pictureDTOs = pictureService.getOwerPictures(regItemDO.getItemId(), (short) 2);
			if (pictureDTOs != null && pictureDTOs.size() > 0) {
				itemDetailDTO.setPictures(pictureDTOs);
			}
			//查询项目可用店铺
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("查询项目配图出错！ItemServiceImpl.getItemDetail(), regItemDO = " + regItemDO);
		}
		List<ShopItemDTO> listShop = shopItemService.queryShopByItem(itemId, "", 116.3972282409668, 39.90960456049752, city);
		itemDetailDTO.setTotalElements(Long.valueOf(listShop.size()));
		return itemDetailDTO;
	}

	@Override
	public PageableItemDTO querySysItems(Integer page, Integer size,
			Integer sortType) throws NumberFormatException, ServiceException {

		
		Sort.Direction direction = Sort.Direction.DESC;
        if (SortTypeEnum.POSITIVE_SEQUENCE.getValue().equals(sortType)) {
            direction = Sort.Direction.ASC;
        }
        Pageable pageable = new PageRequest(page, size, new Sort(direction,
                "gmtCreate"));
        Page<RegItemDO> pageData = regItemRepository.findAll(pageable);
        PageableItemDTO pageableItemDTO = new PageableItemDTO();
        pageableItemDTO.setTotalPages(pageData.getTotalPages());
        pageableItemDTO.setTotalElements(pageData.getTotalElements());
        List<ItemDetailDTO> itemDetailDtoList = new ArrayList<>();
        if(pageData.getContent()!=null){
        	pageData.getContent().forEach((recordDo)->{
        		ItemDetailDTO 	itemDetailDto = itemService.getItemDetail(recordDo.getItemId());
        		itemDetailDtoList.add(itemDetailDto);
        	});
        }
        pageableItemDTO.setRecordList(itemDetailDtoList);
        System.out.println("系统项目分页列表："+pageableItemDTO.toString());
		return pageableItemDTO;
	}

}
